package com.atguigu.gmall.user.service.impl;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.util.IpUtil;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.mapper.UserAddressMapper;
import com.atguigu.gmall.user.mapper.UserInfoMapper;
import com.atguigu.gmall.user.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserService {
    @Autowired
    UserInfoMapper userInfoMapper;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    UserAddressMapper userAddressMapper;

    @Override
    public UserInfo login(UserInfo info) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<UserInfo>();
        wrapper.eq("login_name",info.getLoginName());

        String passwd = info.getPasswd();
        String encrypt = MD5.encrypt(passwd);
        wrapper.eq("passwd",encrypt);


        UserInfo userInfo = userInfoMapper.selectOne(wrapper);
        return userInfo;
    }

    /**
     * 1、用户登录成功，给前端返回
     *    {
     *        code: xxx
     *        message: "",
     *        data: {
     *            token: "登录成功后生成的令牌"
     *            nickName: "昵称"
     *        }
     *    }
     * 2、用户登录成功，给redis存用户信息
     *   user:info:你的token（有过期时间）
     *   存的值： {"userId",1,"ipAddr":"xxxxxx"}
     *
     * 3、下次前端任何请求，自己带上 token 的cookie
     * @param userInfo
     * @param request
     * @return
     */
    @Override
    public Map<String, Object> hanleLoginSuccess(UserInfo userInfo, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        //1、用户登录成功以后，生成一个唯一令牌(token)。
        // 标识用户身份。用户id，到底是谁，存在redis中。 前端只要收到返回结果，自己会存cookie，而且放大了作用域
        String token = UUID.randomUUID().toString().replace("-", "");
        map.put("token",token);
        map.put("nickName",userInfo.getNickName());

        //2、将用户登录的信息，存到redis
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        //准备给redis中保存的用户信息
        Map<String,Object> loginUser = new HashMap<>();
        loginUser.put("userId",userInfo.getId());
        //未来，权限验证，拿到token，去redis中查登录的用户，userId, ipAddr
        String ipAddress = IpUtil.getIpAddress(request);
        loginUser.put("ipAddr",ipAddress); //防止非法盗用

        String string = null;
        try {
            string = new ObjectMapper().writeValueAsString(loginUser);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }


        //把用户信息存到redis中
        operations.set(RedisConst.USER_LOGIN_KEY_PREFIX + token,string,RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
        return map;
    }

    @Override
    public void loginOut(String token) {
        String s = RedisConst.USER_LOGIN_KEY_PREFIX + token;
        redisTemplate.delete(s);
    }

    @Override
    public List<UserAddress> getUserAddressListByUserId(String userId) {
        QueryWrapper<UserAddress> wrapper = new QueryWrapper<>();
        //SQL
        wrapper.eq("user_id",Long.parseLong(userId));
        return userAddressMapper.selectList(wrapper);
    }
}
